package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.config.WebSocketConfig;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.BeanHelper;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.beans.beancontext.BeanContext;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {

    @Resource
    private AddressBookMapper addressBookMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private WeChatPayUtil weChatPayUtil;

    @Resource
    private WebSocketServer webSocketServer;

    /**
     * @description: 提交订单
     * @author: tanbobin
     * @date: 2024/6/6 11:00
     * @param:
     * @param ordersSubmitDTO
     * @return:
     * @return com.sky.vo.OrderSubmitVO
     **/
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) throws IOException {
        log.info("用户下单了。。。。");
        //0.查询收件地址信息，地址为空，不能下单
        AddressBook addressBook = addressBookMapper.queryAddressById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new BusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //0.购物车数据为空，不能下单
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (CollectionUtils.isEmpty(shoppingCartList)){
            throw new BusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1.保存订单数据
        Orders orders = BeanHelper.copyProperties(ordersSubmitDTO, Orders.class);
        orders.setNumber(String.valueOf(System.nanoTime()));    // 订单号 IdWorker --- 可以 使用 雪花算法
        orders.setStatus(Orders.ORDER_STAUTS_PENDING_PAYMENT);  // 待付款
        orders.setUserId(BaseContext.getCurrentId());           // 用户id
        orders.setOrderTime(LocalDateTime.now());               // 下单时间
        orders.setPayStatus(Orders.PAY_STATUS_PAID);            // 支付状态 未支付

        // 收货人
        orders.setPhone(addressBook.getPhone());                // 手机号
        orders.setAddress(addressBook.getDetail());             // 详细地址
        orders.setConsignee(addressBook.getConsignee());        // 收货人

        ordersMapper.insert(orders);

        //2.保存订单明细数据
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(cart -> {
            // 拷贝属性
            OrderDetail orderDetail = BeanHelper.copyProperties(cart, OrderDetail.class);
            // 赋值订单id
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());

        // 2.1 批量添加订单明细
        orderDetailMapper.insertBatch(orderDetailList);

        //3.清空当前用户的购物车数据
        shoppingCartMapper.delete(shoppingCart);

        //4.组装数据并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        //5.推送消息给管理端 -提醒新订单
        HashMap<Object, Object> paramMap = new HashMap<>();
        paramMap.put("type", 1);
        paramMap.put("orderId", orders.getId());
        paramMap.put("content", "订单号: " + orders.getNumber());

        log.info("向客户端推送消息, {}", paramMap);

        webSocketServer.sendMessageToAllClient(JSONObject.toJSONString(paramMap));

        return orderSubmitVO;
    }

    /**
     * 订单支付
     * 复制粘贴的代码
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new BusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    /**
     * 支付成功，修改订单状态
     * 复制粘贴的代码
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.ORDER_STAUTS_TO_BE_CONFIRMED)
                .payStatus(Orders.PAY_STATUS_PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * @description: 客户催单
     * @author: tanbobin
     * @date: 2024/6/11 11:32
     * @param:
     * @param id
     * @return:
     **/
    @Override
    public void reminder(Long id) throws IOException {
        // 获取订单信息
        Orders order = ordersMapper.getOrderById(id);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("type", 2);
        paramMap.put("orderId", id);
        paramMap.put("content", "订单号: " + order.getNumber());
        webSocketServer.sendMessageToAllClient(JSONObject.toJSONString(paramMap));
    }

    /**
     * @description: 订单搜索
     * @author: tanbobin
     * @date: 2024/6/11 17:25
     * @param:
     * @param pageQueryDTO
     * @return:
     * @return java.util.List<com.sky.result.PageResult>
     **/
    @Override
    public PageResult search(OrdersPageQueryDTO pageQueryDTO) {
        //1. 设置分页参数
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        //2. 执行分页查询
        List<Orders> ordersList = ordersMapper.list(pageQueryDTO);

        // 2.1 判断返回的结果是否为空
        if (ordersList.isEmpty()){
            throw new BusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //3. 解析分页结果
        PageInfo pageInfo = new PageInfo(ordersList, pageQueryDTO.getPageSize());

        //处理查询出来的原始结果
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * @description: 订单状态统计
     * @author: tanbobin
     * @date: 2024/6/11 18:09
     * @param:
     * @return:
     * @return com.sky.vo.OrderStatisticsVO
     **/
    @Override
    public OrderStatisticsVO orderStatistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        //待接单数量
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.ORDER_STAUTS_TO_BE_CONFIRMED);

        //待派送数量
        Integer confirmed = ordersMapper.countStatus(Orders.ORDER_STAUTS_CONFIRMED);

        //派送中数量
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.ORDER_STAUTS_DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();

        return orderStatisticsVO;
    }

    /**
     * @description: 根据ID查询订单详情
     * @author: tanbobin
     * @date: 2024/6/11 20:29
     * @param:
     * @param id
     * @return:
     * @return com.sky.vo.OrderVO
     **/
    @Override
    public OrderVO getOrderDetailsById(Long id) {
        // 1. 查询订单基本信息
        Orders order = ordersMapper.getOrderById(id);

        // 2. 查询订单详情(明细)
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailsById(id);

        // 3. 封装数据并返回
        OrderVO orderVO = BeanHelper.copyProperties(order, OrderVO.class);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * @description: 接单
     * @author: tanbobin
     * @date: 2024/6/11 20:52
     * @param:
     * @param confirmDTO
     * @return:
     **/
    @Override
    public void orderConfirm(OrdersConfirmDTO confirmDTO) {

        // 把订单状态修改为 已接单 3
        confirmDTO.setStatus(Orders.ORDER_STAUTS_CONFIRMED);
        Orders order = BeanHelper.copyProperties(confirmDTO, Orders.class);


        ordersMapper.update(order);

//        // 1. 根据订单id查询数据
//        Orders order = ordersMapper.getOrderById(confirmDTO.getId());
//
//        // 1.1 把订单状态修改为 已接单 3
//        order.setStatus(3);

    }

    /**
     * @description: 拒单
     * @author: tanbobin
     * @date: 2024/6/11 21:04
     * @param:
     * @param rejectionDTO
     * @return:
     **/
    @Override
    public void orderRejection(OrdersRejectionDTO rejectionDTO) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrderById(rejectionDTO.getId());

        // 订单只有存在且状态为 2 （待接单）才可以拒单
        if (order == null || !order.getStatus().equals(Orders.ORDER_STAUTS_TO_BE_CONFIRMED)){
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        order.setStatus(Orders.ORDER_STAUTS_CANCELLED);
        order.setRejectionReason(rejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());

        ordersMapper.update(order);
    }

    /**
     * @description: 取消订单
     * @author: tanbobin
     * @date: 2024/6/11 21:32
     * @param:
     * @param cancelDTO
     * @return:
     **/
    @Override
    public void orderCancel(OrdersCancelDTO cancelDTO) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrderById(cancelDTO.getId());

        // 订单只有存在且状态不为 6 （已取消）才可以取消订单
        if (order == null || order.getStatus().equals(Orders.ORDER_STAUTS_CANCELLED)){
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.ORDER_STAUTS_CANCELLED);
        order.setId(cancelDTO.getId());
        order.setCancelTime(LocalDateTime.now());
        order.setCancelReason(cancelDTO.getCancelReason());

        ordersMapper.update(order);
    }

    /**
     * @description: 派送订单
     * @author: tanbobin
     * @date: 2024/6/11 21:31
     * @param:
     * @param id
     * @return:
     **/
    @Override
    public void orderDelivery(Long id) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrderById(id);

        // 订单只有存在且状态为 3 （待派送）才能派送订单
        if (order == null || !order.getStatus().equals(Orders.ORDER_STAUTS_CONFIRMED)){
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .status(Orders.ORDER_STAUTS_DELIVERY_IN_PROGRESS)
                .id(id)
                .build();

        ordersMapper.update(orders);
    }

    /**
     * @description: 完成订单
     * @author: tanbobin
     * @date: 2024/6/11 21:43
     * @param:
     * @param id
     * @return:
     **/
    @Override
    public void orderComplete(Long id) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrderById(id);

        // 订单只有存在且状态为 4 （派送中）才能完成订单
        if (order == null || !order.getStatus().equals(Orders.ORDER_STAUTS_DELIVERY_IN_PROGRESS)){
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.ORDER_STAUTS_COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        order.setId(id);

        ordersMapper.update(order);

    }

}
